import 'package:flutter/material.dart';
import '../constants/colors.dart';
import '../constants/spacing.dart';
import '../constants/text_styles.dart';
import 'photo_viewer_screen.dart';

/// 相机历史半屏弹窗
class CameraHistorySheet extends StatefulWidget {
  const CameraHistorySheet({super.key});

  @override
  State<CameraHistorySheet> createState() => _CameraHistorySheetState();
}

class _CameraHistorySheetState extends State<CameraHistorySheet> {
  int _selectedTab = 0; // 0: 全部, 1: 未导入, 2: 已导入
  String _selectedCard = '卡1';
  final List<String> _cards = ['卡1', '卡2'];

  // 模拟照片数据
  final List<Map<String, dynamic>> _photos = List.generate(
    12,
    (index) => {
      'id': index,
      'filename': 'FUJIfil...${index + 1}.JPG',
      'tags':
          index % 3 == 0 ? ['重复', '过曝'] : (index % 3 == 1 ? ['虚焦'] : ['闭眼']),
      'imported': index % 2 == 0,
    },
  );

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: [Color(0xFF1F1F1F), Color(0xFF0F0F0F)],
        ),
        borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
      ),
      child: Column(
        children: [
          // 拖拽手柄
          const SizedBox(height: 12),
          Container(
            width: 40,
            height: 4,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(2),
            ),
          ),
          _buildHeader(),
          _buildToolbar(),
          _buildTimeSelector(),
          Expanded(
            child: _buildPhotoGrid(),
          ),
        ],
      ),
    );
  }

  /// 构建顶部标题栏
  Widget _buildHeader() {
    return Container(
      height: 56,
      padding: const EdgeInsets.symmetric(horizontal: 16),
      child: Stack(
        children: [
          Center(
            child: Text(
              '相机历史',
              style: AppTextStyles.heading3.copyWith(
                color: Colors.white,
                fontWeight: FontWeight.w500,
                fontSize: 16,
              ),
            ),
          ),
          Positioned(
            right: 0,
            top: 0,
            bottom: 0,
            child: IconButton(
              icon: Container(
                width: 24,
                height: 24,
                decoration: BoxDecoration(
                  color: Colors.white.withOpacity(0.06),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: const Icon(
                  Icons.close,
                  size: 16,
                  color: Colors.white,
                ),
              ),
              onPressed: () => Navigator.pop(context),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建工具栏（Tabs + 卡选择）
  Widget _buildToolbar() {
    // 计算数量
    final totalCount = _photos.length;
    final importedCount = _photos.where((p) => p['imported'] == true).length;
    final notImportedCount =
        _photos.where((p) => p['imported'] == false).length;

    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16),
      child: Row(
        children: [
          // Tabs
          Expanded(
            child: Row(
              children: [
                _buildTab('全部 $totalCount', 0),
                const SizedBox(width: 12),
                _buildTab('未导入 $notImportedCount', 1),
                const SizedBox(width: 12),
                _buildTab('已导入 $importedCount', 2),
              ],
            ),
          ),
          // 卡选择
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
            decoration: BoxDecoration(
              color: Colors.white.withOpacity(0.1),
              borderRadius: BorderRadius.circular(12),
            ),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(
                  _selectedCard,
                  style: AppTextStyles.body2.copyWith(
                    color: Colors.white.withOpacity(0.56),
                    fontSize: 12,
                  ),
                ),
                const SizedBox(width: 4),
                Icon(
                  Icons.expand_more,
                  size: 16,
                  color: Colors.white.withOpacity(0.56),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildTab(String label, int index) {
    final isSelected = _selectedTab == index;
    return GestureDetector(
      onTap: () => setState(() => _selectedTab = index),
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
        decoration: BoxDecoration(
          color: isSelected
              ? Colors.white.withOpacity(0.2)
              : Colors.white.withOpacity(0.05),
          borderRadius: BorderRadius.circular(6),
        ),
        child: Text(
          label,
          style: AppTextStyles.body2.copyWith(
            color: isSelected ? Colors.white : Colors.white.withOpacity(0.56),
            fontSize: 12,
          ),
        ),
      ),
    );
  }

  /// 构建时间选择器和功能按钮
  Widget _buildTimeSelector() {
    return Container(
      padding: const EdgeInsets.all(16),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          // 时间选择器和多选框
          Row(
            children: [
              Container(
                padding:
                    const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
                decoration: BoxDecoration(
                  color: Colors.white.withOpacity(0.06),
                  borderRadius: BorderRadius.circular(14),
                ),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text(
                      '时间轴',
                      style: AppTextStyles.body2.copyWith(
                        color: Colors.white,
                        fontSize: 12,
                      ),
                    ),
                    const SizedBox(width: 4),
                    Icon(
                      Icons.sort,
                      size: 16,
                      color: Colors.white,
                    ),
                  ],
                ),
              ),
            ],
          ),
          // 功能按钮
          Row(
            children: [
              _buildToolButton('筛选', Icons.filter_list),
              const SizedBox(width: 8),
              _buildToolButton('排序', Icons.sort),
              const SizedBox(width: 8),
              _buildToolButton('全选', Icons.check_box_outline_blank),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildToolButton(String label, IconData icon) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(icon, size: 16, color: Colors.white.withOpacity(0.4)),
          const SizedBox(width: 4),
          Text(
            label,
            style: AppTextStyles.body2.copyWith(
              color: Colors.white.withOpacity(0.4),
              fontSize: 12,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建照片网格
  Widget _buildPhotoGrid() {
    // 根据选中的 tab 过滤照片
    List<Map<String, dynamic>> filteredPhotos;
    if (_selectedTab == 0) {
      // 全部
      filteredPhotos = _photos;
    } else if (_selectedTab == 1) {
      // 未导入
      filteredPhotos = _photos.where((p) => p['imported'] == false).toList();
    } else {
      // 已导入
      filteredPhotos = _photos.where((p) => p['imported'] == true).toList();
    }

    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 8),
      child: GridView.builder(
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 3,
          crossAxisSpacing: 4,
          mainAxisSpacing: 8,
          childAspectRatio: 0.75,
        ),
        itemCount: filteredPhotos.length,
        itemBuilder: (context, index) {
          return _buildPhotoCard(filteredPhotos[index]);
        },
      ),
    );
  }

  /// 构建照片卡片
  Widget _buildPhotoCard(Map<String, dynamic> photo) {
    final bool imported = photo['imported'];
    final List<String> tags = photo['tags'];

    return Column(
      children: [
        // 照片和标签
        Expanded(
          child: GestureDetector(
            onTap: () => _showPhotoViewer(photo['id']),
            child: Container(
              decoration: BoxDecoration(
                color: Colors.grey[800],
                borderRadius: BorderRadius.circular(4),
              ),
              child: Stack(
                children: [
                  // 照片占位
                  Container(
                    decoration: BoxDecoration(
                      color: Colors.grey[700],
                      borderRadius: BorderRadius.circular(4),
                    ),
                  ),
                  // 文件名
                  Positioned(
                    left: 0,
                    right: 0,
                    bottom: 0,
                    child: Container(
                      padding: const EdgeInsets.symmetric(
                          horizontal: 4, vertical: 8),
                      decoration: BoxDecoration(
                        gradient: LinearGradient(
                          begin: Alignment.topCenter,
                          end: Alignment.bottomCenter,
                          colors: [
                            Colors.transparent,
                            Colors.black.withOpacity(0.5),
                          ],
                        ),
                      ),
                      child: Text(
                        photo['filename'],
                        style: AppTextStyles.body2.copyWith(
                          color: Colors.white.withOpacity(0.9),
                          fontSize: 11,
                          fontWeight: FontWeight.w500,
                          shadows: [
                            Shadow(
                              color: Colors.black.withOpacity(0.25),
                              offset: const Offset(0, 1),
                              blurRadius: 2,
                            ),
                          ],
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                  ),
                  // AI标签
                  if (tags.isNotEmpty)
                    Positioned(
                      top: 4,
                      left: 4,
                      child: Row(
                        children: tags.take(2).map((tag) {
                          return Container(
                            margin: const EdgeInsets.only(right: 4),
                            width: 20,
                            height: 20,
                            decoration: BoxDecoration(
                              color: Colors.black.withOpacity(0.42),
                              border: Border.all(
                                color: Colors.white.withOpacity(0.2),
                                width: 1,
                              ),
                              borderRadius: BorderRadius.circular(12),
                            ),
                            child: Icon(
                              _getTagIcon(tag),
                              size: 12,
                              color: Colors.white.withOpacity(0.8),
                            ),
                          );
                        }).toList(),
                      ),
                    ),
                ],
              ),
            ),
          ),
        ),
        // 按钮
        const SizedBox(height: 2),
        Row(
          children: [
            if (imported) ...[
              Expanded(
                child: _buildActionButton('舍弃'),
              ),
              const SizedBox(width: 3),
              Expanded(
                child: _buildActionButton('选择'),
              ),
            ] else ...[
              Expanded(
                child: _buildActionButton('导入'),
              ),
            ],
          ],
        ),
      ],
    );
  }

  Widget _buildActionButton(String label) {
    return Container(
      height: 32,
      decoration: BoxDecoration(
        color: Colors.white.withOpacity(0.08),
        borderRadius: BorderRadius.circular(4),
      ),
      child: Center(
        child: Text(
          label,
          style: AppTextStyles.body2.copyWith(
            color: Colors.white,
            fontSize: 12,
          ),
        ),
      ),
    );
  }

  IconData _getTagIcon(String tag) {
    switch (tag) {
      case '重复':
        return Icons.content_copy;
      case '过曝':
        return Icons.wb_sunny;
      case '虚焦':
        return Icons.blur_on;
      case '闭眼':
        return Icons.remove_red_eye;
      default:
        return Icons.help_outline;
    }
  }

  /// 显示照片查看器
  void _showPhotoViewer(int photoId) {
    // 准备照片列表和标题
    final List<String> photos =
        _photos.map((p) => p['filename'] as String).toList();
    final List<String> titles =
        _photos.map((p) => p['filename'] as String).toList();

    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => PhotoViewerScreen(
          photos: photos,
          initialIndex: photoId,
          titles: titles,
        ),
      ),
    );
  }
}
